package dev.pda.display.util

import com.jeremyliao.liveeventbus.LiveEventBus
import dev.pda.display.Constants
import java.io.InputStream
import java.net.ServerSocket
import java.net.Socket

open class TCPManager() {
    private var serverSocket: ServerSocket? = null
    private var client: Socket? = null
    private var inputStream: InputStream? = null

    companion object {
        private var instance: TCPManager? = null
            get() {
                if (field == null) {
                    field = TCPManager()
                }
                return field
            }

        @Synchronized
        fun get(): TCPManager {
            return instance!!
        }
    }

    fun init(port: Int) {
        try {
            serverSocket = ServerSocket(port)
            client = serverSocket?.accept()
            inputStream = client?.getInputStream()
            receiveMessage()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun receiveMessage() {
        while (true) {
            try {
                val buf = ByteArray(1024)
                val len: Int? = inputStream?.read(buf)
                if (len != null && len != -1) {
                    val text = String(buf, 0, len)
                    LiveEventBus.get(Constants.RECEIVER_TCP_MESSAGE).post(text)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}